"""
auth:xgt-python
datetime:2021/11/18
数据处理可视化
"""
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Pie, Bar, Timeline

# 读取数据
df = pd.read_csv('weather.csv', encoding='utf-8')
# print(df['日期'])

df['日期'] = df['日期'].apply(lambda x: pd.to_datetime(x))
# print(df['日期'])

df['month'] = df['日期'].dt.month
# print(df['month'])

df_agg = df.groupby(['month', '天气']).size().reset_index()
# print(df_agg)
df_agg.columns = ['month', 'tianqi', 'count']
# print(df_agg)
data = df_agg[df_agg['month'] == 1][['tianqi', 'count']] \
    .sort_values(by='count', ascending=False).values.tolist()

# print(data)

"""[['阴', 22], ['多云', 20], ['霾', 14], ['晴', 6]]"""

# 画图

# 时间顺序
timeline = Timeline()
# 播放设置:设置时间间隔 1s
timeline.add_schema(play_interval=1000)

for month in df_agg['month'].unique():
    data = (
        df_agg[df_agg['month'] == month][['tianqi', 'count']]
            .sort_values(by='count', ascending=True)
            .values.tolist()
    )
    # 绘制柱状图
    bar = Bar()
    # x轴数据:天气名称
    bar.add_xaxis([x[0] for x in data])
    # y轴数据；出现次数
    bar.add_yaxis('', [x[1] for x in data])

    # 让柱状图横着放
    bar.reversal_axis()
    # 将计数标签放置在图形右边
    bar.set_series_opts(label_opts=opts.LabelOpts(position='right'))
    # 设置下图表的名称
    bar.set_global_opts(title_opts=opts.TitleOpts(title='宣城2019年每月天气变化'))
    # 将设置好的bar对象放置到时间轮播图当中，并且标签选择月份
    timeline.add(bar, f'{month}月')

# 将设置好的图表保存为html文件
timeline.render('weather.html')
